/*=========================================================================
  UberSim Source Code Release
  -------------------------------------------------------------------------
  Copyright (C) 2002 Manuela Veloso, Brett Browning, Mike Bowling,
  James Bruce; {mmv, brettb, mhb, jbruce}@cs.cmu.edu
  Erick Tryzelaar {erickt}@andrew.cmu.edu
  School of Computer Science, Carnegie Mellon University
  -------------------------------------------------------------------------
  This software is distributed under the GNU General Public License,
  version 2.  If you do not have a copy of this licence, visit
  www.gnu.org, or write: Free Software Foundation, 59 Temple Place,
  Suite 330 Boston, MA 02111-1307 USA.  This program is distributed
  in the hope that it will be useful, but WITHOUT ANY WARRANTY,
  including MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  -------------------------------------------------------------------------*/

#include "mmgr.h"

#include "Island.h"
#include "RigidBody.h"

Island::Island ()
{
	rigidBodyCount = 0;
}

Island::~Island ()
{
}

RigidBody* Island::getRigidBody (unsigned int index)
{
	RigidBody* rigidBody = 0;

	if (0 <= index && index < rigidBodies.size ())
	{
		rigidBody = rigidBodies[index];
	}

	return rigidBody;
}

unsigned int Island::getRigidBodyCount ()
{
	return rigidBodyCount;
}

void Island::addRigidBody (RigidBody* rigidBody)
{
	if (rigidBody)
	{
		rigidBodyCount++;

		if (rigidBody->getIsland ())
		{
			rigidBody->getIsland ()->removeRigidBody (rigidBody);
		}

		rigidBody->setIsland (this);

		for (unsigned int i = 0; i < rigidBodies.size (); i++)
		{
			if (rigidBodies[i] == 0)
			{
				rigidBodies[i] = rigidBody;
				return;
			}
		}

		rigidBodies.push_back (rigidBody);
	}
}

void Island::removeRigidBody (RigidBody* rigidBody)
{
	if (rigidBody)
	{
		for (unsigned int i = 0; i < rigidBodies.size (); i++)
		{
			if (rigidBodies[i] == rigidBody)
			{
				rigidBodyCount--;
				rigidBodies[i] = 0;
				rigidBody->setIsland (0);

				return;
			}
		}
	}
}

RigidBody* Island::removeRigidBody (unsigned int i)
{
	RigidBody* rigidBody = 0;

	if (0 <= i && i < rigidBodies.size ())
	{
		rigidBody = rigidBodies[i];

		if (rigidBody)
		{
			rigidBodyCount--;
			rigidBodies[i] = 0;
			rigidBody->setIsland (0);
		}
	}

	return rigidBody;
}

unsigned int Island::size ()
{
	return rigidBodies.size ();
}

